package com.lebang.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: tony
 * @Date: 2018-11-05 09:20
 * @Description:    ip地址获取工具类
 */
public class IpUtil {

    public static String getIp(HttpServletRequest request){
        try {
            String xip = request.getHeader("X-Real-IP");
            String xFor = request.getHeader("X-Forwarded-For");
            if(StringUtils.isNotEmpty(xFor) && !"unKnown".equalsIgnoreCase(xFor)){
                //多次反向代理后会有多个ip值，第一个ip才是真实ip
                int index = xFor.indexOf(",");
                if(index != -1){
                    return xFor.substring(0,index);
                }else{
                    return xFor;
                }
            }
            xFor = xip;
            if(StringUtils.isNotEmpty(xFor) && !"unKnown".equalsIgnoreCase(xFor)){
                return xFor;
            }
            if (StringUtils.isBlank(xFor) || "unknown".equalsIgnoreCase(xFor)) {
                xFor = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isBlank(xFor) || "unknown".equalsIgnoreCase(xFor)) {
                xFor = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isBlank(xFor) || "unknown".equalsIgnoreCase(xFor)) {
                xFor = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isBlank(xFor) || "unknown".equalsIgnoreCase(xFor)) {
                xFor = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isBlank(xFor) || "unknown".equalsIgnoreCase(xFor)) {
                xFor = request.getRemoteAddr();
            }
            if("0:0:0:0:0:0:0:1".equals(xFor)){
                xFor="127.0.0.1";
            }
            return xFor;
        }catch (Exception e){
            return "未知ip";
        }

    }

    private static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

}
